package com.sky.AutoFillAspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @projectName: sky-take-out_1
 * @package: com.sky.AutoFillAspect
 * @className: AutoFillAspect
 * @author: Eric
 * @description: TODO
 * @date: 2023/10/12 21:35
 * @version: 1.0
 */
@Component
@Slf4j
@Aspect
public class AutoFillAspect {
    //1.切点
    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void pt(){

    }

    //2.通知方法
    @Before("pt()")
    public void autoFill(JoinPoint joinPoint){
        //动态获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();


        Object arg = joinPoint.getArgs()[0];
        try {
            if (Objects.equals(value,OperationType.INSERT)){
                Method setCreatTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreatUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setCreatTime.invoke(arg,LocalDateTime.now());
                setUpdateTime.invoke(arg,LocalDateTime.now());
                setCreatUser.invoke(arg,BaseContext.getCurrentId());
                setUpdateUser.invoke(arg,BaseContext.getCurrentId());
            }

            if (Objects.equals(value,OperationType.UPDATE)){
                Method setUpdateTime = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setUpdateTime.invoke(arg,LocalDateTime.now());
                setUpdateUser.invoke(arg,BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            log.info("动态注入新增/更新异常:"+e);
        }
    }
}
